package iyoga.controller;

import iyoga.check.CardCheck;
import iyoga.check.MemberCheck;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import tables.card.Card;
import tables.card.CardDAO;
import tables.coach.Coach;
import tables.coach.CoachDAO;
import tables.course.Course;
import tables.course.CourseDAO;
import tables.member.Member;
import tables.member.MemberDAO;
import tables.schedule.Schedule;
import tables.schedule.ScheduleDAO;
import tables.subscribe.Subscribe;
import tables.subscribe.SubscribeDAO;

public class Main {
	/** 
     * 两个时间相差距离多少天多少小时多少分多少秒 
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00 
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00 
     * @return long[] 返回值为：{天, 时, 分, 秒} 
     */  
    public static long[] getDistanceTimes(String str1, String str2) {  
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date one;  
        Date two;  
        long day = 0;  
        long hour = 0;  
        long min = 0;  
        long sec = 0;  
        try {  
            one = df.parse(str1);  
            two = df.parse(str2);  
            long time1 = one.getTime();  
            long time2 = two.getTime();  
            long diff ;  
            if(time1<time2) {  
                diff = time2 - time1;  
            } else {  
                diff = time1 - time2;  
            }  
            day = diff / (24 * 60 * 60 * 1000);  
            hour = (diff / (60 * 60 * 1000) - day * 24);  
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);  
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        long[] times = {day, hour, min, sec};  
        return times;  
    }  
  
	
	public static void main(String[] args) throws ParseException {
		
		MemberDAO mdao = new MemberDAO();
		CardDAO cdao = new  CardDAO();
		CourseDAO coursedao = new CourseDAO();
		CoachDAO coachdao = new CoachDAO();
		ScheduleDAO scheduledao = new ScheduleDAO();
		SubscribeDAO subscribedao = new SubscribeDAO();
		
		String query1 = "from Member";
		List<Member> mlist = mdao.query(query1);      //得到已有会员列表
		int mlen = mlist.size();
		while (true){
			System.out.print(">iyoga ");
			Scanner sc = new Scanner(System.in);    //输入
			String str = sc.next();
			if(str != null && str.equals("quit"))
				break;
			if(str != null && str.equals("add-member")) 
			{
			
				Member mem = new Member();
				MemberCheck membercheck = new MemberCheck();
				String name = sc.next();
				boolean b = true;       //用于判断是否输入有错，有错设为false
				if(!membercheck.checkName(name).equals("ok"))
				{
					b = false;
					System.out.println(membercheck.checkName(name));
				}	
				String address = sc.next();
				if(!membercheck.checkAddress(address).equals("ok"))
				{
					b = false;
					System.out.println(membercheck.checkAddress(address));
				}
				String job = sc.next();
				if(!membercheck.checkJob(job).equals("ok"))
				{
					b = false;
					System.out.println(membercheck.checkJob(job));
				}
				if(b)                 //校验无错后，进行数据库插入
				{
					mem.setAddress(address);
					mem.setJob(job);
					mem.setName(name);
					mlen += 1;
					String numid = "";
					if(mlen <= 9)
					{
						numid = "00"+mlen;
					}
					else if(10 <= mlen&& mlen < 100 )
					{
						numid = "0"+mlen;
					}
					mem.setNum(numid);	
					mdao.AddMember(mem);
					System.out.println(name+"'s member id is "+ numid);
				}				
			}
			if (str != null && str.equals("add-card")) 
			{ 
				boolean bl = true;     //用于判断是否输入有错，有错设为false
				CardCheck cardcheck = new CardCheck();
				String name = sc.next();
				if(!cardcheck.checkName(name).equals("ok"))
				{
					bl = false;
					System.out.println(cardcheck.checkName(name));
				}
				
				String query2 = "from Member mem where mem.name = '" +name+"'";  //通过name得到校园编号 
				List<Member> memlist = mdao.query(query2);
				Member member = null;
				String memnum = "";
				if(memlist.size() > 0)
				{
					member = memlist.get(0);
					memnum = member.getNum();
				}
				String type = sc.next();
				if(!cardcheck.checkType(type).equals("ok"))
				{
					bl = false;
					System.out.println(cardcheck.checkType(type));
				}
				
				Card card = new Card();
				Date date = new Date(System.currentTimeMillis());     
				Timestamp nowdate = new Timestamp(date.getTime());
				
			    
				if(type.equals("年卡") && bl)
				{
					Calendar calendar = Calendar.getInstance();   
				    calendar.setTime(date);
				    calendar.add(Calendar.YEAR, +1);
				    date = calendar.getTime();
					Timestamp enddate = new Timestamp(date.getTime());
					card.setType(1);
					card.setPeriod(1);
					card.setStart(nowdate);
					card.setEnd(enddate);
					card.setTimes(0);
					card.setIsvalid(1);
					card.setNum(memnum);
					cdao.AddCard(card);
					System.out.println("A new 年卡 added to "+name+"("+member.getNum()+")");
				}
				if(type.equals("次卡") && bl)
				{
					Calendar calendar = Calendar.getInstance();   
				    calendar.setTime(date);
				    calendar.add(Calendar.YEAR, +3);
				    date = calendar.getTime();
					Timestamp enddate = new Timestamp(date.getTime());
					int times = sc.nextInt();
					if(cardcheck.checkTimes(times).equals("ok"))
					{
						card.setType(2);
						card.setPeriod(3);
						card.setStart(nowdate);
						card.setEnd(enddate);
						card.setTimes(times);
						card.setIsvalid(1);
						card.setNum(memnum);
						cdao.AddCard(card);
						System.out.println("A new 次卡 with "+times+" times added to "+name);
					}
					else
					{
						System.out.println(cardcheck.checkTimes(times));
						
					}
					
				}

			}
			if (str != null && str.equals("add-course"))
			{
				String coures_name = sc.next();
				Course course = new Course();
				course.setName(coures_name);
				course.setNum(30);
				coursedao.Add(course);
				System.out.println("课程["+coures_name+"]添加成功");
			}
			if (str != null && str.equals("add-coach"))
			{
				String coach_name = sc.next();
				String family = sc.next();
				String age_str = sc.next();
				int length = age_str.length();
				age_str = age_str.substring(0,length - 1);
				int age = Integer.parseInt(age_str);
				String skill = sc.next();
				Coach coach = new Coach();
				coach.setAge(age);
				coach.setFamily(family);
				coach.setName(coach_name);
				coach.setSkill(skill);
				coachdao.Add(coach);
				System.out.println("教练["+coach_name+"]添加成功");
			}
			if (str != null && str.equals("schedule"))
			{
				String schedule_num = sc.next();
				String course_name = sc.next();
				String coach_name = sc.next();
				Schedule schedule = new Schedule();
				schedule.setScheduleNum(schedule_num);
				
				String query_course = "from Course cou where cou.name = '" +course_name+"'";
				List<Course> courselist = coursedao.query(query_course);
				String query_coach = "from Coach co where co.name = '" +coach_name+"'";
				List<Coach> coachlist = coachdao.query(query_coach);
				if(courselist.size() > 0 && coachlist.size() > 0)
				{
					schedule.setCoachId(coachlist.get(0).getId());
					schedule.setCourseId(courselist.get(0).getId());
					scheduledao.Add(schedule);
					System.out.println("排课成功");
				}
				
			}
			if (str != null && str.equals("subscribe"))
			{
				String subscribe_num = sc.next();
				String mem_name = sc.next();
				
				String query2 = "from Member mem where mem.name = '" +mem_name+"'";  //通过name得到会员编号 
				List<Member> memlist = mdao.query(query2);
				Member member = null;
				String memnum = "";
				if(memlist.size() > 0)
				{
					member = memlist.get(0);
					memnum = member.getNum();
					Subscribe sub = new Subscribe();
					String query_subscribe = "from Subscribe sub where sub.scheduleNum='"+subscribe_num+"'";
					List<Subscribe> sublist= subscribedao.query(query_subscribe);
					String query_schedule = "from Schedule sch where sch.scheduleNum='"+subscribe_num+"'";
					List<Schedule> schedulelist = scheduledao.query(query_schedule);
					Course course = coursedao.findById(schedulelist.get(0).getCourseId());
					Coach coach = coachdao.findById(schedulelist.get(0).getCoachId());
					
					if(sublist.size() > 30)
					{
						System.out.println("人数已满");
					}
					else
					{
						sub.setScheduleNum(subscribe_num);
						sub.setMemberNum(memnum);
						subscribedao.Add(sub);
						System.out.println(mem_name + "预定成功,请于"+subscribe_num.substring(0,4)+"年"
								+subscribe_num.substring(4,6)+"月"+subscribe_num.substring(6,8)+"日"+subscribe_num.substring(9,11)
								+":"+subscribe_num.substring(11,13)+"准时到剑瑜伽馆，修炼"+coach.getName()+"老师的"+course.getName()
								);
					}
				}
				
				
			}
			if (str != null && str.equals("cancel"))
			{
				String subscribe_num = sc.next();
				String mem_name = sc.next();
				Date time = new Date();

				// 声明日期格式化类变量

				DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				// 日期格式转化为字符串格式

				String time_now = df.format(time.getTime());
				String time_str = subscribe_num.substring(0,4) +"-"+subscribe_num.substring(4,6)+"-"+subscribe_num.substring(6,8)+
						         " "+subscribe_num.substring(9,11)+":"+subscribe_num.substring(11,13)+":00";
				// 字符串格式转化为日期格式

//				Date new_time = df.parse(time_str);
				long[] times = getDistanceTimes(time_str,time_now);
				if(times[0] >= 1 || times[1] > 2)
				{
					String hql="delete from Subscribe sub where sub.scheduleNum='"+subscribe_num+"'";
					subscribedao.delete(hql);
					System.out.println("取消预约课程，必须在开课两小时之前");
				}
				else
				{
					System.out.println("不能取消预约，必须在开课两小时之前");
				}
				
				
			}
			
		}
	}

}
